# Create your views here.
from django_redis import get_redis_connection
from rest_framework.generics import RetrieveAPIView, UpdateAPIView, CreateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework_jwt.views import ObtainJSONWebToken

import constants
from goods.models import SKU
from goods.serializers import SKUSerializer
from oauth.utils import check_save_user_token
from users import serializers
from users.models import User
from users.serializers import AddUserBrowsingHistorySerializer
from users.utils import merge_cookie_cart


class UserDetailView(RetrieveAPIView):
	"""
	用户详情
	"""
	serializer_class = serializers.UserDetailSerializer
	permission_classes = [IsAuthenticated]

	def get_object(self):
		return self.request.user


class EmailView(UpdateAPIView):
	"""
	保存用户邮箱
	"""
	permission_classes = [IsAuthenticated]
	serializer_class = serializers.EmailSerializer

	def get_object(self, *args, **kwargs):
		return self.request.user


class EmailVerifyView(APIView):
	"""
	用户邮件认证
	"""
	def get(self, request, *args, **kwargs):
		token = request.query_params.get('token')

		if not token:
			raise Response({'message': 'token丢失'}, status=400)

		data = check_save_user_token(token)

		user_id = data.get('user_id')
		email = data.get('email')

		if not user_id or not email:
			raise Response({'message': 'token解析错误'}, status=400)

		try:
			user = User.objects.get(id=user_id)
		except Exception as e:
			raise Response({'message': 'token中的用户不存在'}, status=400)

		user.email_active = True
		user.save()

		return user


class UserBrowsingHistoryView(CreateAPIView):
	"""
	用户浏览历史记录
	"""

	serializer_class = AddUserBrowsingHistorySerializer
	permission_classes = [IsAuthenticated]

	def get(self, request):
		"""
		获取历史
		"""
		user_id = request.user.id

		redis_conn = get_redis_connection("history")
		history = redis_conn.lrange("history_%s" % user_id, 0, constants.USER_BROWSING_HISTORY_COUNTS_LIMIT - 1)
		skus = []
		# 为了保持查询出的顺序与用户的浏览历史保存顺序一致
		for sku_id in history:
			sku = SKU.objects.get(id=sku_id)
			skus.append(sku)

		s = SKUSerializer(skus, many=True)
		return Response(s.data)



class UserAuthorizeView(ObtainJSONWebToken):
	"""
	重写认证的post视图，增加新的合并购物车的功能
	"""

	def post(self, request, *args, **kwargs):
		response = super().post(request, *args, **kwargs)

		serializer = self.get_serializer(data=request.data)
		if serializer.is_valid():
			user = serializer.object.get('user') or request.user
			response = merge_cookie_cart(request, user, response)

		return response
